package com.nulldev.util.security.encryptAPI_rw.impls.idea;

import java.io.InputStream;
import java.io.OutputStream;

import com.nulldev.util.VariableAPI.MathUtil;
import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Charsets.CharsetUtil;
import com.nulldev.util.security.encryptAPI_rw.api.ICipherType;
import com.nulldev.util.security.encryptAPI_rw.api.IStandardBlockingCipher;
import com.nulldev.util.security.encryptAPI_rw.api.IStandardStreamingCipher;

public class IDEACipher implements IStandardBlockingCipher, IStandardStreamingCipher {

	private static final String[] CIPHER_NAMES =
		{ "IDEA", "Idea" };

	@Override
	public String getEncryptorID() {
		return "ecr_v3.internal.idea";
	}

	@Override
	public String[] getCipherNames() {
		return CIPHER_NAMES;
	}

	@Override
	public long encrypt(final InputStream is, final OutputStream os, final byte[] privateKey) {
		Variables.requireNonNull(is, "is");
		Variables.requireNonNull(os, "os");
		Variables.requireNonNull(privateKey, "privateKey");
		long count = 0;
		final InternalIdeaCipher idea = new InternalIdeaCipher(new String(privateKey, CharsetUtil.UTF_8), true);
		final byte[] b = new byte[8];
		try {
			while ((count += (is.read(b, 0, 8))) != -1) {
				idea.crypt(b);
				os.write(b, 0, 8);
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		return count;
	}

	@Override
	public long decrypt(final InputStream is, final OutputStream os, final byte[] privateKey) {
		Variables.requireNonNull(is, "is");
		Variables.requireNonNull(os, "os");
		Variables.requireNonNull(privateKey, "privateKey");
		long count = 0;
		final InternalIdeaCipher idea = new InternalIdeaCipher(new String(privateKey, CharsetUtil.UTF_8), false);
		final byte[] b = new byte[8];
		try {
			while ((count += (is.read(b, 0, 8))) != -1) {
				idea.crypt(b);
				os.write(b, 0, 8);
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		return count;
	}

	@Override
	public byte[] encrypt(final byte[] data, final byte[] key) {
		final InternalIdeaCipher idea = new InternalIdeaCipher(new String(Variables.requireNonNullObject(key, "key"), CharsetUtil.UTF_8), true);
		final byte[] out = new byte[MathUtil.padToInterval(Variables.requireNonNullObject(data, "data").length, 8)];
		System.arraycopy(data, 0, out, 0, data.length);
		for (int i = 0; i < data.length; i += 8)
			idea.crypt(out, i);
		return out;
	}

	@Override
	public byte[] decrypt(final byte[] data, final byte[] key) {
		final InternalIdeaCipher idea = new InternalIdeaCipher(new String(Variables.requireNonNullObject(key, "key"), CharsetUtil.UTF_8), false);
		final byte[] out = new byte[MathUtil.padToInterval(Variables.requireNonNullObject(data, "data").length, 8)];
		System.arraycopy(data, 0, out, 0, data.length);
		for (int i = 0; i < data.length; i += 8)
			idea.crypt(out, i);
		return out;
	}

	@Override
	public ICipherType getCipherType() {
		return ICipherType.PRIVATE_KEY;
	}
}
